<template>
  <div class="card-form">
    <el-form ref="form" :model="registerForms" label-width="195px" :disabled="ifDisabled" :rules="rules" label-position="left" style="padding: 0 0 0 40px;">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="成立日期" prop="startDate" style="margin-bottom: 12px;">
            <el-date-picker type="date" placeholder="请选择" v-model="registerForms.startDate" size="small" value-format="yyyy-MM-dd" clearable></el-date-picker>
          </el-form-item>
          <el-form-item label="注册号" prop="registerId" style="margin-bottom: 12px;">
            <el-input class="input" v-model="registerForms.registerId" size="small" clearable></el-input>
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="creditCode" style="margin-bottom: 12px;">
            <el-input v-model="registerForms.creditCode" size="small" clearable></el-input>
          </el-form-item>
          <el-form-item label="原币" prop="orginalCurrency" style="margin-bottom: 12px; margin-left: -9px">
            <el-select v-model="registerForms.orginalCurrency" size="small" filterable style="width: calc(100% - 9px); margin-left: 9px" clearable>
              <el-option
                v-for="item in moneyType"
                :key="item.index"
                :label="item.description"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="limitCompany" label="注册股份数" prop="shareRegister" style="margin-bottom: 12px;">
            <el-input class="input" v-model="registerForms.shareRegister" size="small" clearable></el-input>
          </el-form-item>
          <el-form-item v-if="ifShareCompany" label="已缴款股份数" prop="sharePaid" style="margin-bottom: 12px;">
            <el-input class="input" v-model="registerForms.sharePaid" size="small" disabled></el-input>
          </el-form-item>
          <el-form-item v-if="!ifShareCompany" label="实收资本总额(原币)" prop="stockPaidOc" style="margin-bottom: 12px;">
            <el-input class="input" v-model="registerForms.stockPaidOc" size="small" disabled clearable></el-input>
          </el-form-item>
          <el-form-item v-if="!ifPartnerAdd" label="法定代表人" prop="operName" style="margin-bottom: 12px;">
            <el-input v-model="registerForms.operName" disabled :class="ifDisabled?'input':'select-btn'" size="small"></el-input>
            <el-button type="text" v-show="!ifDisabled" @click="handleDialogShow">选择</el-button>
            <!-- <img v-show="!ifDisabled" src="../../../assets/img/sousuo.png" style="width: 20px; height: 20px;"> -->
            <!-- <i v-show="!ifDisabled" class="el-icon-circle-plus-outline" style="font-size: 16px"></i> -->
          </el-form-item>
          <el-form-item v-if="ifPartnerAdd" label="合伙人委派代表" prop="operName" style="margin-bottom: 12px;">
            <el-input v-model="registerForms.operName" disabled :class="ifDisabled?'input':'select-btn'" size="small"></el-input>
            <el-button type="text" v-show="!ifDisabled" @click="handleDialogShowPartnerDebuty">选择</el-button>
          </el-form-item>
          <el-form-item v-if="ifPartnerAdd" label="执行事务合伙人" prop="executivePartnerName" style="margin-bottom: 12px;">
            <el-input v-model="registerForms.executivePartnerName" disabled :class="ifDisabled?'input':'select-btn'" size="small"></el-input>
            <el-button type="text" v-show="!ifDisabled" @click="handleDialogShowPartner">选择</el-button>
          </el-form-item>
          <el-form-item label="注册地址" prop="registerAddress" style="margin-bottom: 12px;">
            <el-tooltip class="item" effect="dark" :content="registerForms.registerAddress" placement="top">
              <el-input class="input" v-model="registerForms.registerAddress" size="small" clearable></el-input>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="经营地址" prop="businessAddress" style="margin-bottom: 12px;">
            <el-tooltip class="item" effect="dark" :content="registerForms.businessAddress" placement="top">
              <el-input class="input" v-model="registerForms.businessAddress" size="small" clearable></el-input>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="招商局行业分类" prop="cmhkBusinessType" style="margin-bottom: 12px; margin-left: -9px">
            <el-select v-model="registerForms.cmhkBusinessType" size="small" style="width: calc(100% - 9px); margin-left: 9px" clearable>
              <el-option
                v-for="item in cmhkBusinessType"
                :key="item.index"
                :label="item.value"
                :disabled="item.isValid==='1'?false:true"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商业登记号码" prop="businessRegisterId" style="margin-bottom: 12px;">
            <el-input class="input" v-model="registerForms.businessRegisterId" size="small" clearable></el-input>
          </el-form-item>
          <el-form-item label="注册类型小类" prop="registerTypeDetail" style="margin-bottom: 12px;">
            <el-select v-model="registerForms.registerTypeDetail" size="small" filterable clearable class="input">
              <el-option
                v-for="item in registerDetailTypeOption"
                :key="item.index"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="营业期限至" prop="endDate" style="margin-bottom: 12px;">
            <el-date-picker type="date" placeholder="请选择" v-model="registerForms.endDate" size="small" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :disabled="ifAlwaysWork" clearable></el-date-picker>
          </el-form-item>
          <el-form-item label="是否永续经营" prop="isContinue" style="margin-bottom: 12px;">
            <el-select v-model="registerForms.isContinue" size="small" filterable class="input" @change="alwaysWorkSelect" clearable>
              <el-option
                v-for="item in boleenOption"
                :key="item.index"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否离岸法域注册" prop="isRegisterOutside" style="margin-bottom: 12px;">
            <el-select v-model="registerForms.isRegisterOutside" size="small" filterable class="input" clearable disabled>
              <el-option
                v-for="item in boleenOption"
                :key="item.index"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="注册资本(原币)" prop="registeredCapitalOc" style="margin-bottom: 12px; margin-left: -9px">
            <el-input v-model.trim="registerForms.registeredCapitalOc" size="small" style="width: calc(100% - 9px); margin-left: 9px" clearable></el-input>
          </el-form-item>
           <el-form-item label="注册资本(人民币)" prop="registeredCapitalRmb" style="margin-bottom: 12px;">
            <el-input class="input" v-model.trim="registerForms.registeredCapitalRmb" size="small" disabled clearable></el-input>
          </el-form-item>
          <el-form-item v-if="ifShareCompany" label="已缴款股本(原币)" prop="stockPaidOc" style="margin-bottom: 12px;">
            <el-input class="input" v-model="registerForms.stockPaidOc" size="small" disabled></el-input>
          </el-form-item>
          <el-form-item label="所在地区" prop="location" style="margin-bottom: 12px; margin-left: -9px">
            <el-cascader
              v-model="registerForms.location"
              :options="options"
              @change="handleChange"
              :props="prop"
              size="small"
              filterable
              style="width: calc(100% - 9px); margin-left: 9px"
              clearable></el-cascader>
          </el-form-item>
          <el-form-item v-if="ifPartnerAdd" label="执行事务合伙人社会信用代码" prop="executivePartnerUcc" style="margin-bottom: 12px;">
            <el-input class="input" v-model="registerForms.executivePartnerUcc" size="small" clearable></el-input>
          </el-form-item>
          <el-form-item v-if="limitCompany" label="秘书公司" prop="secretaryName" style="margin-bottom: 12px;">
            <el-input v-model="registerForms.secretaryName" disabled :class="ifDisabled?'input':'select-btn'" size="small"></el-input>
            <el-button v-show="!ifDisabled" type="text" @click="handleDialogShowSecretary">选择</el-button>
          </el-form-item>
          <el-form-item label="注册地址坐标" prop="registerAddressCode" style="margin-bottom: 12px;">
            <el-input class="input" v-model="registerForms.registerAddressCode" size="small" clearable></el-input>
          </el-form-item>
          <el-form-item label="经营地址坐标" prop="businessAddressCode" style="margin-bottom: 12px;">
            <el-input class="input" v-model="registerForms.businessAddressCode" size="small" clearable></el-input>
          </el-form-item>
          <el-form-item label="国民经济行业分类" prop="countryBusinessTypeDes" style="margin-bottom: 12px;">
            <el-tooltip class="item" effect="dark" :content="registerForms.countryBusinessTypeDes" placement="top">
              <el-input class="input" v-model="registerForms.countryBusinessTypeDes" size="small" @focus="inputFocus"></el-input>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="组织机构代码" prop="organizationCode" style="margin-bottom: 12px;">
            <el-input class="input" v-model="registerForms.organizationCode" size="small" disabled clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="经营范围" prop="businessRange" style="margin-bottom: 12px;">
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="registerForms.businessRange" maxlength="1000" show-word-limit clearable></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark" style="margin-bottom: 12px;">
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="registerForms.remark" maxlength="1000" show-word-limit clearable></el-input>
      </el-form-item>        
    </el-form>
    <!-- 选择国民经济行业类型弹窗 -->
    <el-dialog title="选择国民经济行业分类" :visible.sync="dialogVisibleTree" width="60%">
      <div class="tree-box">
        <el-tree
          ref="tree"
          :data="treeData"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          :default-checked-keys="checkdId"
          :default-expanded-keys="expandId"
          :check-strictly="true"
          @check="listCheckd">
        </el-tree>
      </div>
      <span slot="footer">
        <el-button @click="dialogVisibleTree = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitTree">确 定</el-button>
      </span>
    </el-dialog>
    <MemberAndCompany @sendData="getDialogData" :dialogData="dialogData" />
    <AddMember @sendData="getPeopleDialogData" :selectPeopleDialog="selectPeopleDialog" />
  </div>
</template>

<script>
import MemberAndCompany from './components/memberAndCompany.vue'
import AddMember from './components/addMember.vue'
import { queryRegisterMsgHistory, editRegisterMsgHistroy, addRegisterMsg, countryBusinessTypes, cmbusinessTypes, fcompanyTypes, queryRegisterinfo, moneyType, allArea, editRegisterFormal, queryRegisterDetailType } from '@/api/modules/propertyRight.js'
import { checkNumber } from '@/utils/pattern.js'
export default {
  components: {
    MemberAndCompany,
    AddMember
  },
  props: {
    registerForm: {
      type: Object,
      required: true
    }
  },
  watch: {
    registerForm: {
      handler(val) {
        this.ifDisabled = val.ifDisabled
      },
      deep: true
    }
  },
  data() {
    return {
      ifDisabled: true,
      ifShareCompany: false,
      ifPartnerAdd: false,
      registerForms: {
        location: [],
        operName: '',
        operCode: '',
        executivePartnerName: '',
        executivePartner: '',
        isPerson: '',
        partnerType: '',
        secretary: '',
        secretaryName: '',
        secretaryType: '',
        countryBusinessTypeDes: '',
        sharePaid: '',
        countryBusinessType: [],
        selectId: [],
        executivePartnerUcc: '',
        registerTypeDetail: ''
      },
      rules: {
        cmhkBusinessType: [{ required: true, message: '请选择分类', trigger: 'change' }],
        registeredCapitalOc: [
          { required: true, message: '请输入注册资本(原币)', trigger: 'change' },
          { validator: checkNumber, trigger: 'change' }
        ],
        shareRegister: [{ validator: checkNumber, trigger: 'change' }],
        orginalCurrency: [{ required: true, message: '请选择原币', trigger: 'change' }],
        location: [{ required: true, message: '请选择地区', trigger: 'blur' }]
      },
      cmhkBusinessType: [],
      fcompanyType: [],
      registerDetailTypeOption: [],
      moneyType: [],
      boleenOption: [
        {value: '是', code: '1'},
        {value: '否', code: '0'}
      ],
      ifAlwaysWork: false,
      stripe: true,
      limitCompany: true, // 控制有限责任公司下字段显示
      options: [],
      prop: {
        label: 'name',
        value: 'code',
        children: 'child'
      },
      saveId: {
        cmhkId: ''
      },
      saveRegisterType: '',
      // 国民经济行业类型
      dialogVisibleTree: false,
      treeData: [],
      defaultProps: {
        label: 'value',
        children: 'child'
      },
      saveStr: '',
      checkdId: [],
      expandId: [],
      // 执行事务合伙人/合伙人委派代表选人弹窗
      dialogData: {
        dialogVisible: false,
        shareTitle: ''
      },
      // 法定代表人选人弹窗
      selectPeopleDialog: {
        dialogVisible: false
      },
      // 保存历史数据查询参数用于修改
      saveHistroyParams: {}
    }
  },
  methods: {
    // 查询注册信息(此方法在父组件中调用)
    getRegisterinfo(params) {
      console.log(params)
      this.saveId.cmhkId = params.cmhkId
      this.saveRegisterType = params.registerType
      queryRegisterinfo(this.saveId).then(res => {
        if (res.data.code === '0') {
          this.registerForms = res.data.body
          let str = res.data.body.countryBusinessType
          let arr = str.split(',')
          this.checkdId = arr
          this.expandId = res.data.body.expandId
          if (res.data.body.isContinue === '1') {
            this.registerForms.endDate = ''
            this.ifAlwaysWork = true
          }
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 查询注册信息历史数据(此方法在父组件中调用)
    getRegisterinfoHistory(params) {
      this.saveHistroyParams = params
      queryRegisterMsgHistory(params).then(res => {
        if (res.data.code === '200') {
          this.registerForms = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 修改注册信息（此方法在父组件中调用）
    editRegisterinfo() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          editRegisterFormal(this.registerForms).then(res => {
            if (res.data.code === '0') {
              this.$message.success('修改管控信息成功')
              this.getRegisterinfo(this.saveId)
              this.ifDisabled = true
              this.$emit('changeState', this.ifDisabled)
            } else {
              this.$message.error(res.data.message)
            }
          })
        } else {
          return false
        }
      })
    },
    // 修改注册信息历史数据(此方法在父组件中调用)
    editRegisterHistroyinfo() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const obj = Object.assign(this.registerForms, this.saveHistroyParams)
          editRegisterMsgHistroy(obj).then(res => {
            if (res.data.code === '200') {
              this.$message.success('修改管控信息历史数据成功')
              this.getRegisterinfoHistory(this.saveHistroyParams)
              this.ifDisabled = true
              this.$emit('changeState', this.ifDisabled)
            } else {
              this.$message.error(res.data.message)
            }
          })
        } else {
          return false
        }
      })
    },
    // 移除校验结果
    removeRequired() {
      this.$refs['form'].clearValidate()
    },
    // 查询注册信息下拉（此方法在父组件中调用）
    getOption() {
      // 招商局行业分类
      cmbusinessTypes().then(res => {
        if (res.data.code === '0') {
          this.cmhkBusinessType = res.data.body
        } else {
          this.$message.error('获取招商局行业分类数据失败')
        }
      })
      // 所属地区
      allArea().then(res => {
        if (res.data.code === '0') {
          this.options = this.getTreeData(res.data.body)
        } else {
          this.$message.error('获取地区数据失败')
        }
      })
      // 外商企业投资类型
      fcompanyTypes().then(res => {
        if (res.data.code === '0') {
          this.fcompanyType = res.data.body
        } else {
          this.$message.error('获取外商企业投资类型数据失败')
        }
      })
      // 原币
      moneyType().then(res => {
        if (res.data.code === '0') {
          this.moneyType = res.data.body
        } else {
          this.$message.error('获取原币数据失败')
        }
      })
      // 根据父组件传来的的注册类型请求注册类型小类的数据
      const obj = {
        code: this.saveRegisterType,
        tableName: "company",
        field: "register_type"
      }
      queryRegisterDetailType(obj).then(res => {
        this.registerDetailTypeOption = res.data.data
      })
    },
    getTreeData(data){
      // 循环遍历json数据
      for (let i=0; i<data.length; i++) {
        if (data[i].child.length<1) {
          // children若为空数组，则将children设为undefined
          data[i].child = null
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].child)
        }
      }
      return data
    },
    // 选择所在地区
    handleChange(val) {
      this.registerForm.location = val
    },
    // 显示选择法定代表人弹窗
    handleDialogShow() {
      this.selectPeopleDialog.dialogVisible = true
    },
    getPeopleDialogData(data) {
      if (data.value === ''||data.code === '') {
        this.selectPeopleDialog.dialogVisible = false
      } else {
        this.registerForms.operName = data.value
        this.registerForms.operCode = data.code
        this.selectPeopleDialog.dialogVisible = false
      }
    },
    // 显示执行事务合伙人选择弹窗
    handleDialogShowPartner() {
      this.dialogData.dialogVisible = true
      this.dialogData.shareTitle = '执行事务合伙人'
    },
    handleDialogShowPartnerDebuty() {
      this.dialogData.dialogVisible = true
      this.dialogData.shareTitle = '合伙人委派代表'
    },
    handleDialogShowSecretary() {
      this.dialogData.dialogVisible = true
      this.dialogData.shareTitle = '秘书公司'
    },
    getDialogData(data) {
      console.log(data)
      if (this.dialogData.shareTitle === '合伙人委派代表') {
        if (data.appointType === ''||data.code === '') {
          this.dialogData.dialogVisible = false
          this.dialogData.shareTitle = ''
        } else {
          this.registerForms.operCode = data.code
          this.registerForms.isPerson = data.appointType
          this.$set(this.registerForms, 'operName', data.value)
          this.dialogData.dialogVisible = false
          this.dialogData.shareTitle = ''
        }
      } else if (this.dialogData.shareTitle === '执行事务合伙人') {
        if (data.isPerson === ''||data.code === '') {
          this.dialogData.dialogVisible = false
          this.dialogData.shareTitle = ''
        } else {
          this.registerForms.executivePartner = data.code
          this.registerForms.partnerType = data.isPerson
          this.registerForms.executivePartnerUcc = data.executivePartnerUcc
          this.$set(this.registerForms, 'executivePartnerName', data.value)
          this.dialogData.dialogVisible = false
          this.dialogData.shareTitle = ''
        }
      } else if (this.dialogData.shareTitle === '秘书公司') {
        if (data.code === ''||data.isPerson === '') {
          this.dialogData.dialogVisible = false
          this.dialogData.shareTitle = ''
        } else {
          this.registerForms.secretary = data.code
          this.registerForms.secretaryType = data.isPerson
          this.$set(this.registerForms, 'secretaryName', data.value)
          this.dialogData.dialogVisible = false
          this.dialogData.shareTitle = ''
        }
      } 
    },
    // 是否永续经营选是时 经营日期置空且不可用
    alwaysWorkSelect(val) {
      if (val === '1') {
        this.registerForms.endDate = ''
        this.ifAlwaysWork = true
      } else {
        this.ifAlwaysWork = false
      }
    },
    // 国民经济行业分类input聚焦时 出现选择树
    inputFocus() {
      this.dialogVisibleTree = true
      countryBusinessTypes().then(res => {
        if (res.data.code  === '200') {
          this.treeData = this.handleTreeDisabled(res.data.data[0].child)
        }
      })
    },
    handleTreeDisabled(data) {
      for(let i=0; i<data.length; i++) {
        if (data[i].child.length!=0) {
          data[i].disabled = true
          this.handleTreeDisabled(data[i].child)
        }
      }
      return data
    },
    listCheckd(data) {
      let arr = []
      let arr2 = []
      arr = this.$refs.tree.getCheckedNodes()
      arr.forEach(item => {
        arr2.push(item.value)
      })
      let str = arr2.join(',')
      this.saveStr = str
      this.registerForms.selectId = this.$refs.tree.getCheckedKeys()
    },
    // 点击确定给国民经济行业分类赋值
    handleSubmitTree() {
      let str = this.registerForms.selectId.join(',')
      this.registerForms.countryBusinessType = str
      this.registerForms.countryBusinessTypeDes = this.saveStr
      this.dialogVisibleTree = false
    },
    // 根据公司类型(有限责任公司)删除公司股份数和公司秘书字段(在父组件中调用)
    delinput() {
      this.limitCompany = false
      this.ifShareCompany = false
    },
    addinput() {
      this.limitCompany = true
      this.ifShareCompany = true
    },
    // 根据公司类型(合伙人企业)添加合伙人三个字段(在父组件中调用)
    partnerAdd() {
      this.ifPartnerAdd = true
    },
    partnerDel() {
      this.ifPartnerAdd = false
    }
  }
}
</script>

<style lang="less" scoped>
  .card-form {
    margin-top: 10px;
    width: calc(100% - 25px);
    .input {
      width: 100%;
    }
    .select-btn {
      width: calc(100% - 40px);
    }
    .table-box {
      height: 40vh;
    }
    .partner-box {
      height: 40vh;
    }
    .tree-box {
      height: 50vh;
      overflow: auto;
    }
  }
</style>
<style>
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }
  .el-input.is-disabled .el-input__inner {
    background-color:rgb(228,231,237,0.15);
    border-color: #E4E7ED;
    color: #606266;
  }
  .el-textarea.is-disabled .el-textarea__inner {
    background-color: rgb(228,231,237,0.15);
    border-color: #E4E7ED;
    color: #606266;
  }
</style>